<template>
	<div class="wrapper">
		<!-- header部分 -->
		<header>
			<p>确认订单</p>
		</header>

		<!-- 订单信息部分（类名与结构完全保留原有样式） -->
		<div class="order-info">
			<h5>订单配送至：</h5>
			<div class="order-info-address" @click="toUserAddress">
				<!-- 显示完整地址信息：联系人+电话+地址 -->
				<p>{{selectedAddress ? `${selectedAddress.contactName} ${selectedAddress.contactTel} ${selectedAddress.address}` : '请选择送货地址'}}
				</p>
				<i class="fa fa-angle-right"></i>
			</div>
		</div>

		<h3>{{business?.businessName}}</h3>

		<!-- 订单明细部分（类名完全保留原有样式） -->
		<ul class="order-detailed">
			<!-- 循环购物车获取的当前商家商品，匹配原有DOM结构 -->
			<li v-for="item in orderItems" :key="item.food.id">
				<div class="order-detailed-left">
					<img :src="item.food.foodImg" :alt="item.food.foodName">
					<p>{{item.food.foodName}} x {{item.quantity}}</p>
				</div>
				<p>&#165;{{(item.food.foodPrice * item.quantity).toFixed(2)}}</p>
			</li>
		</ul>
		<div class="order-deliveryfee">
			<p>配送费</p>
			<p>&#165;{{business?.deliveryPrice || 0}}</p>
		</div>

		<!-- 合计部分（类名与结构完全保留原有样式） -->
		<div class="total">
			<div class="total-left">
				合计：&#165;{{totalSettle.toFixed(2)}}
			</div>
			<div class="total-right" @click="toPayment">
				提交订单
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'Orders',
		data() {
			return {
				businessId: this.$route.query.businessId,
				business: {}, // 商家信息（从接口获取）
				orderItems: [], // 订单商品（从购物车接口筛选当前商家商品）
				selectedAddress: null, // 选中的配送地址
				userAddresses: [], // 用户地址列表
				selectedAddressId: this.$route.query.selectedAddressId || null // 从路由获取选中地址ID
			}
		},
		created() {
			const token = localStorage.getItem('id_token');
			if (!token) {
				this.$router.push('/login');
				return;
			}

			// 初始化：获取商家信息、购物车商品、用户地址
			this.getBusinessInfo(token);
			this.getCartItems(token);
			this.getUserAddresses(token);
		},
		computed: {
			// 计算结算总价（匹配原有逻辑，调整商品价格字段）
			totalSettle() {
				// 从购物车商品中计算商品总价
				const goodsTotal = this.orderItems.reduce((total, item) => {
					return total + (item.food.foodPrice * item.quantity);
				}, 0);
				// 商品总价 + 配送费
				return goodsTotal + (this.business?.deliveryPrice || 0);
			}
		},
		methods: {
			// 1. 获取商家信息（调整字段匹配后端响应）
			getBusinessInfo(token) {
				this.$axios.get(`businesses/${this.businessId}`, {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				}).then(response => {
					const result = response.data;
					if (result.success && result.code === 200) {
						this.business = result.data; // 后端返回的商家数据直接赋值
					} else {
						alert('获取商家信息失败：' + (result.message || '未知错误'));
					}
				}).catch(error => {
					console.error('获取商家信息出错：', error);
				});
			},

			// 2. 从购物车接口获取当前商家的商品（核心功能优化）
			getCartItems(token) {
				this.$axios.get(`carts?businessId=${this.businessId}`, {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				}).then(response => {
					const result = response.data;
					if (result.success && result.code === 200) {
						// 核心：business.id转字符串，与this.businessId（字符串）匹配
						this.orderItems = result.data.filter(item => {
							return item.business.id.toString() === this.businessId;
						});
					} else {
						console.warn('获取购物车列表失败：', result.message);
						this.orderItems = [];
					}
				}).catch(error => {
					console.error('获取购物车列表出错：', error);
					this.orderItems = [];
				});
			},

			// 3. 获取用户地址列表（确保选中地址正确显示）
			getUserAddresses(token) {
				this.$axios.get('addresses', {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				}).then(response => {
					const result = response.data;
					if (result.success && result.code === 200) {
						this.userAddresses = result.data || [];

						// 核心：将selectedAddressId和地址id都转成字符串，确保类型匹配
						const targetId = this.selectedAddressId?.toString();
						if (targetId) {
							const selectedAddr = this.userAddresses.find(
								addr => addr.id.toString() === targetId
							);
							this.selectedAddress = selectedAddr || null;
						} else {
							const defaultAddr = this.userAddresses.find(addr => addr.isDefault);
							this.selectedAddress = defaultAddr || (this.userAddresses[0] || null);
						}
					} else {
						console.warn('获取地址列表失败：', result.message);
						this.userAddresses = [];
					}
				}).catch(error => {
					console.error('获取地址列表出错：', error);
					this.userAddresses = [];
				});
			},

			// 4. 前往选择地址页面（保留原有跳转逻辑）
			toUserAddress() {
				this.$router.push({
					path: '/userAddress',
					query: {
						businessId: this.businessId,
						from: 'orders' // 标识来源，无需额外参数
					}
				});
			},

			// 5. 提交订单（调整商品字段匹配后端要求）
			toPayment() {
				if (!this.selectedAddress) {
					alert('请选择送货地址！');
					return;
				}
				if (this.orderItems.length === 0) {
					alert('订单商品为空，请返回重新选择！');
					return;
				}

				const token = localStorage.getItem('id_token');
				// 准备订单数据（匹配后端接口字段）
				const orderData = {
					business: {
						id: this.businessId
					},
					deliveryAddress: {
						id: this.selectedAddress.id
					},
					orderItems: this.orderItems.map(item => ({
						food: {
							id: item.food.id
						},
						quantity: item.quantity,
						unitPrice: item.food.foodPrice
					})),
					orderTotal: this.totalSettle
				};

				// 创建订单
				this.$axios.post('orders', orderData, {
					headers: {
						'Authorization': `Bearer ${token}`
					}
				}).then(response => {
					const result = response.data;
					if (result.success && result.code === 200) {
						const orderId = result.data.id;
						this.clearCartItems(token); // 清空已下单商品
						// 跳转到支付页
						this.$router.push({
							path: '/payment',
							query: {
								orderId: orderId,
								totalAmount: this.totalSettle
							}
						});
					} else {
						alert('创建订单失败：' + (result.message || '未知错误'));
					}
				}).catch(error => {
					console.error('创建订单出错：', error);
					alert('创建订单时发生错误，请稍后重试');
				});
			},

			// 6. 清空购物车已下单商品（调整字段匹配购物车接口）
			clearCartItems(token) {
				this.orderItems.forEach(item => {
					this.$axios.patch('carts', {
						foodId: item.food.id,
						businessId: this.businessId,
						quantity: 0
					}, {
						headers: {
							'Authorization': `Bearer ${token}`
						}
					}).catch(error => {
						console.error(`清空商品 ${item.food.id} 失败：`, error);
					});
				});
			}
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		height: 100%;
	}

	/****************** header部分 ******************/
	.wrapper header {
		width: 100%;
		height: 12vw;
		background-color: #0097FF;
		color: #fff;
		font-size: 4.8vw;

		position: fixed;
		left: 0;
		top: 0;
		z-index: 1000;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	/****************** 订单信息部分 ******************/
	.wrapper .order-info {
		/*注意这里，不设置高，靠内容撑开。因为地址有可能折行*/
		width: 100%;
		margin-top: 12vw;
		background-color: #0097EF;
		box-sizing: border-box;
		padding: 2vw;
		color: #fff;
	}

	.wrapper .order-info h5 {
		font-size: 3vw;
		font-weight: 300;
	}

	.wrapper .order-info .order-info-address {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;

		font-weight: 700;
		user-select: none;
		cursor: pointer;
		margin: 1vw 0;
	}

	.wrapper .order-info .order-info-address p {
		width: 90%;
		font-size: 5vw;
	}

	.wrapper .order-info .order-info-address i {
		font-size: 6vw;
	}

	.wrapper .order-info p {
		font-size: 3vw;
	}

	.wrapper h3 {
		box-sizing: border-box;
		padding: 3vw;
		font-size: 4vw;
		color: #666;
		border-bottom: solid 1px #DDD;
	}

	/****************** 订单明细部分 ******************/
	.wrapper .order-detailed {
		width: 100%;
	}

	.wrapper .order-detailed li {
		width: 100%;
		height: 16vw;
		box-sizing: border-box;
		padding: 3vw;
		color: #666;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.wrapper .order-detailed li .order-detailed-left {
		display: flex;
		align-items: center;
	}

	.wrapper .order-detailed li .order-detailed-left img {
		width: 10vw;
		height: 10vw;
	}

	.wrapper .order-detailed li .order-detailed-left p {
		font-size: 3.5vw;
		margin-left: 3vw;
	}

	.wrapper .order-detailed li p {
		font-size: 3.5vw;
	}

	.wrapper .order-deliveryfee {
		width: 100%;
		height: 16vw;
		box-sizing: border-box;
		padding: 3vw;
		color: #666;
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-size: 3.5vw;
	}

	/****************** 订单合计部分 ******************/
	.wrapper .total {
		width: 100%;
		height: 14vw;

		position: fixed;
		left: 0;
		bottom: 0;

		display: flex;
	}

	.wrapper .total .total-left {
		flex: 2;
		background-color: #505051;
		color: #fff;
		font-size: 4.5vw;
		font-weight: 700;
		user-select: none;

		display: flex;
		justify-content: center;
		align-items: center;
	}

	.wrapper .total .total-right {
		flex: 1;
		background-color: #38CA73;
		color: #fff;
		font-size: 4.5vw;
		font-weight: 700;
		user-select: none;
		cursor: pointer;

		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>